"""
MCP Server Startup Script
========================

This script starts the EmailQA ActionRequiredLogger MCP server.
Supports both stdio and HTTP transport modes.
"""

import sys
import os
import logging
import time

# Add src directory to Python path
sys.path.append('src')

from src.mcp.action_required_logger import mcp, action_logger, run_http_server

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def main():
    """Main function to start the MCP server"""
    print("=" * 60)
    print("EmailQA ActionRequiredLogger MCP Server")
    print("=" * 60)
    print()
    
    # Check if we should run in HTTP mode
    http_mode = '--http' in sys.argv
    
    if http_mode:
        print("Running in HTTP mode...")
        print("Server Information:")
        print(f"  - Tool Name: ActionRequiredLogger")
        print(f"  - API Mode: {'Test Client' if action_logger.use_test_client else 'HTTP Requests'}")
        if not action_logger.use_test_client:
            print(f"  - API Endpoint: {action_logger.api_endpoint}")
        print(f"  - Transport: HTTP")
        print()
        
        # Parse command line arguments
        host = 'localhost'
        port = 8080
        debug = '--debug' in sys.argv
        
        for i, arg in enumerate(sys.argv):
            if arg == '--host' and i + 1 < len(sys.argv):
                host = sys.argv[i + 1]
            elif arg == '--port' and i + 1 < len(sys.argv):
                port = int(sys.argv[i + 1])
        
        print(f"  - Host: {host}")
        print(f"  - Port: {port}")
        print(f"  - Debug: {debug}")
        print()
        print("Available Endpoints:")
        print("  - POST /api/mcp/action_required_logger")
        print("  - GET /api/mcp/check_health")
        print("  - GET /api/mcp/tools")
        print()
        print("Starting HTTP server...")
        print("Press Ctrl+C to stop the server")
        print("=" * 60)
        print()
        
        try:
            # Run the HTTP MCP server
            run_http_server(host=host, port=port, debug=debug)
        except KeyboardInterrupt:
            print("\nServer stopped by user")
        except Exception as e:
            logger.error(f"Server error: {e}")
            print(f"Server error: {e}")
            sys.exit(1)
    else:
        print("Running in stdio mode...")
        print("Server Information:")
        print(f"  - Tool Name: ActionRequiredLogger")
        print(f"  - API Mode: {'Test Client' if action_logger.use_test_client else 'HTTP Requests'}")
        if not action_logger.use_test_client:
            print(f"  - API Endpoint: {action_logger.api_endpoint}")
        print(f"  - Transport: stdio")
        print()
        print("Available Tools:")
        print("  - action_required_logger: Submit email processing tasks")
        print("  - check_api_health: Check API health status")
        print()
        print("Starting stdio server...")
        print("Press Ctrl+C to stop the server")
        print("=" * 60)
        print()
        
        try:
            # Run the MCP server
            mcp.run()
        except KeyboardInterrupt:
            print("\nServer stopped by user")
        except Exception as e:
            logger.error(f"Server error: {e}")
            print(f"Server error: {e}")
            sys.exit(1)

if __name__ == "__main__":
    main()